package com.yongxing.plugin;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.yongxing.pluginstandard.PluginInterfaceActivity;

import java.lang.reflect.Constructor;

public class ProxyActivity extends Activity {

    private String className;
    private PluginInterfaceActivity mPayInterfaceActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        className = getIntent().getStringExtra("className");
        Log.e("jiang", "onCreate:" + className);

        // 通过Class.forName是无法加载的

        try {
            Class<?> aClass = getClassLoader().loadClass(className);
            Constructor<?> constructor = aClass.getConstructor(new Class[]{});
            Object newInstance = constructor.newInstance(new Object[]{});
            mPayInterfaceActivity = (PluginInterfaceActivity) newInstance;
            mPayInterfaceActivity.attach(this);

            Bundle bundle = new Bundle();
            mPayInterfaceActivity.onCreate(bundle);
        } catch (Exception e) {
            Log.e("jiang", "onCreate:" + e.toString());
            e.printStackTrace();
        }

    }

    @Override
    public void setContentView(int layoutResID) {
        Log.e("jiang", "setContentView:" + layoutResID);
        super.setContentView(layoutResID);
    }

    @Override
    public ClassLoader getClassLoader() {
        return PluginManager.getInstance().getClassLoader();
    }

    @Override
    public Resources getResources() {
        return PluginManager.getInstance().getResources();
    }

    /**
     * 在插件中想要开启Activity，需要在ProxyActivity中重写startActivity方法
     *
     * @param intent
     */
    @Override
    public void startActivity(Intent intent) {
        String className1 = intent.getStringExtra("className");
        Intent intent1 = new Intent(this, ProxyActivity.class);
        intent1.putExtra("className", className1);
        super.startActivity(intent1);
    }

    @Override
    public ComponentName startService(Intent service) {
        String serviceName = service.getStringExtra("serviceName");
        Intent intent1 = new Intent(this, ProxyService.class);
        intent1.putExtra("serviceName", serviceName);
        return super.startService(intent1);
    }

    @Override
    public <T extends View> T findViewById(int id) {
        Log.e("jiang", "findViewById:" + id);
        return super.findViewById(id);
    }

    @Override
    public void sendBroadcast(Intent intent) {
        super.sendBroadcast(intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mPayInterfaceActivity.onStart();
    }
}
